import { defineStore } from "pinia";
import { useSocketStore } from "./useSocketStore";
import { useUser } from "./useUser";
import { v4 as uuidv4 } from "uuid";

export const useMsg = defineStore("msg", {
  state: () => ({
    messages: {},
    talkList: [],
    currentImKey: "",
    msgAudioStatus: false, // 消息声音状态
    msgUnreadCount: 0, // 消息未读数量
    noReadMsgKeys: {}, // 未读消息数量
  }),
  getters: {
    getMessages: (state) => state.messages,
    getTalkList: (state) => state.talkList,
    getCurrentImKey: (state) => state.currentImKey,
    getTalkListLength: (state) => state.talkList.length,
    getCurrentTalkInfo: (state) =>
      state.talkList.find((item) => item.imKey === state.currentImKey),
    getCurrentMsgList: (state) => state.messages[state.currentImKey] || [],
    getMsgAudioStatus: (state) => state.msgAudioStatus,
    getMsgUnreadCount: (state) => {
      const keys = Object.keys(state.noReadMsgKeys);
      console.log("getMsgUnreadCount keys:", keys);
      if (keys.length) {
        let num = 0;
        for (let i = 0; i < keys.length; i++) {
          num += state.noReadMsgKeys[keys[i]];
        }
        return num || 0;
      }
      return 0;
    },
    getTalkNoReadMsgNum: (state) => (user) => {
      const keys = Object.keys(state.noReadMsgKeys);
      if (keys.length === 0) {
        const noReadMsgKeys = localStorage.getItem("noReadMsgKeys");
        if (noReadMsgKeys) {
          state.noReadMsgKeys = JSON.parse(noReadMsgKeys);
        }
      }
      return state.noReadMsgKeys[user] || 0;
    },
  },
  actions: {
    setOnlineStatus(data) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        const talkIndex = this.talkList.findIndex(
          (talkItem) => talkItem.imKey === item.user
        );
        if (talkIndex !== -1) {
          this.talkList[talkIndex].online = item.online;
        }
      }
    },
    setMsgListRead() {
      if (!this.currentImKey) return;
      this.messages[this.currentImKey] = this.messages[this.currentImKey].map((item) => {
        item.read = true;
        return item;
      });
    },
    setTlakItemNoReadNum(msgData) {
      console.log("setTlakItemNoReadNum msgData:", msgData);
      const userNum = this.noReadMsgKeys[msgData.user] || 0;
      this.noReadMsgKeys[msgData.user] = userNum + 1;
      localStorage.setItem("noReadMsgKeys", JSON.stringify(this.noReadMsgKeys));
      // 播放消息提示音
      this.setMsgAudioStatus(true);
      setTimeout(() => {
        this.setMsgAudioStatus(false);
      }, 1000);
    },
    setMsgUnreadCount(count) {
      this.msgUnreadCount = count;
    },
    setMsgAudioStatus(status) {
      this.msgAudioStatus = status;
    },
    setAppointMsgRead(from, msgKeys = []) {
      if (!from || !msgKeys || !msgKeys.length) return;
      for (let i = 0; i < this.messages[from].length; i++) {
        const item = this.messages[from][i];
        if (msgKeys.includes(item.msgKey)) {
          this.messages[from][i].read = true;
        }
      }
    },
    clearMessages() {
      this.messages = {};
    },
    setTalkList(talkList) {
      this.talkList = talkList;
    },
    setCurrentImKey(imKey) {
      this.currentImKey = imKey;
      // 重置当前用户的未读数量
      this.noReadMsgKeys[imKey] = 0;
      localStorage.setItem("noReadMsgKeys", JSON.stringify(this.noReadMsgKeys));
    },
    updateTalkListLastMsg(msg, type = 1) {
      // type=1 用户自己发送  2 收到的消息
      const imgKey = type == 1 ? msg.to : msg.user;
      console.log("setTalkListLastMsg imgKey:", imgKey);
      const findIndex = this.talkList.findIndex(
        (item) => item.user === imgKey || item.toUser === imgKey
      );
      console.log("setTalkListLastMsg findIndex:", findIndex);
      if (findIndex !== -1) {
        console.log("msg:", msg);
        const lastItem = this.talkList[findIndex];
        lastItem.lastMessage = msg.msg || msg;
        lastItem.updateTime = msg.time || Date.now();
        this.talkList[findIndex] = lastItem;
      }
    },
    // 发送消息
    sendMessage(event, data, callback, send = true) {
      const socketStore = useSocketStore();
      if (socketStore.isConnected) {
        const msgKey = uuidv4();
        data.msgKey = msgKey;
        if (send) {
          const cloneData = JSON.parse(JSON.stringify(data));
          if (cloneData.toServiceImKey) {
            cloneData.to = cloneData.toServiceImKey;
            delete cloneData.toServiceImKey;
          }
          socketStore.emit(event, cloneData, callback);
        }
        const userStore = useUser();
        const msgData = {
          from: userStore.getUserInfo.uimKey,
          fromName: userStore.getUserInfo.nickName || userStore.getUserInfo.phonenumber,
          fromAvatar: userStore.getUserInfo.avatar || "",
          fromType: 2,
          to: data.to,
          toName: "",
          toAvatar: "",
          toType: 1,
          content: data.content,
          contentType: data.contentType,
          time: Date.now(),
          msgKey,
          read: false,
          exData: data.exData || {},
        };
        this.addMessage(data.to, msgData);
        this.updateTalkListLastMsg(msgData, 1);
      }
    },
    // 添加消息
    addMessage(imgKey, message) {
      try {
        if (!this.messages[imgKey]) {
          this.messages[imgKey] = [];
          const socketStore = useSocketStore();
          socketStore.emit("chatList", {}, (res) => {
            if (res.code === 200) {
              this.talkList = res.data;
            }
          });
        }
        if (Array.isArray(message)) {
          const newMsgList = [];
          for (let i = 0; i < message.length; i++) {
            const item = message[i];
            // 去重
            const checkMsg = this.messages[imgKey].find(
              (msg) => msg.msgKey === item.msg.msgKey
            );
            if (!checkMsg) {
              newMsgList.push(item.msg);
            }
          }
          this.messages[imgKey].unshift(...newMsgList);
        } else {
          // 去重
          if (!this.messages[imgKey].find((msg) => msg.msgKey === message.msgKey)) {
            this.messages[imgKey].push(message);
          }
        }
      } catch (error) {
        console.error("add message error:", error.message);
      }
    },
  },
});
